package cn.two.dabeiphotov2.controller;

import cn.two.dabeiphotov2.mapper.ProductMapper;
import cn.two.dabeiphotov2.pojo.dto.ProductDto;
import cn.two.dabeiphotov2.pojo.dto.ProductUpdateDto;
import cn.two.dabeiphotov2.pojo.entity.Product;
import cn.two.dabeiphotov2.pojo.vo.ProductAdminVo;
import cn.two.dabeiphotov2.pojo.vo.ProductUpdateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;

@RestController
@RequestMapping("/product/")
public class ProductController {
    @Autowired
    ProductMapper mapper;
    @Value("${imagesPath}")
    private String dirPath;

    @RequestMapping("/insert")
    public void insert(@RequestBody ProductDto productDto) {
        Product product = new Product();
        BeanUtils.copyProperties(productDto, product);
        //创建ProductMapper  实现insert方法
        mapper.insert(product);
    }

    @RequestMapping("/select")
    public List<ProductAdminVo> select() {

        return mapper.selectForAdmin();
    }

    @RequestMapping("delete")
    public void delete(int id) {
        String url = mapper.selectUrlById(id);
        new File(dirPath + url).delete();
        mapper.deleteById(id);

    }

    @RequestMapping("update")
    public void update(@RequestBody ProductUpdateDto productUpdateDto) {
        String url = mapper.selectUrlById(productUpdateDto.getId());
        if (!url.equals(productUpdateDto.getUrl())) {
            new File(dirPath + url).delete();
        }

        Product product = new Product();
        BeanUtils.copyProperties(productUpdateDto, product);

        mapper.update(product);
    }

    @RequestMapping("selectById")
    public ProductUpdateVo selectById(int id) {
        return mapper.selectById(id);
    }
}
